#ifndef BMP_H
#define BMP_H
#include "Box.h"

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>

class Bmp : public Box
{
    bool isHyaline = false;
    unsigned int Excludecolor = 0x00000000;

public:
    Bmp(const char *path, bool isHyaline = false, unsigned int Excludecolor = 0x00000000)
    {
        this->isHyaline = isHyaline;
        this->Excludecolor = Excludecolor;
        int fd = open(path, O_RDONLY);
        if (fd == -1)
        {
            cout << path << "图片打开失败" << endl;
            exit(-1);
        }

        // 读取BMP文件头信息
        char header[54];
        if (read(fd, header, 54) != 54 || header[0] != 'B' || header[1] != 'M')
        {
            cout << path << "不是有效的BMP文件" << endl;
            close(fd);
            exit(-1);
        }

        // 获取宽度和高度
        memcpy(&width, header + 18, sizeof(int));
        memcpy(&height, header + 22, sizeof(int));

        // 计算行字节数（4字节对齐）
        int rowSize = ((width * 3 + 3) / 4) * 4;

        // 分配缓冲区
        char *buf = new char[rowSize * height];
        if (buf == nullptr)
        {
            cout << path << "内存分配失败" << endl;
            close(fd);
            exit(-1);
        }

        lseek(fd, 54, SEEK_SET);
        if (read(fd, buf, rowSize * height) != rowSize * height)
        {
            cout << path << "图片读取失败" << endl;
            delete[] buf;
            close(fd);
            exit(-1);
        }

        store = new int[width * height];
        if (store == nullptr)
        {
            cout << path << "图片初始化失败" << endl;
            delete[] buf;
            close(fd);
            exit(-1);
        }

        // 转换BGR到ARGB（BMP是BGR顺序，且上下颠倒）
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                int y = height - 1 - i; // 翻转Y坐标
                int bufIndex = i * rowSize + j * 3;
                int storeIndex = y * width + j;

                unsigned char b = buf[bufIndex + 0];
                unsigned char g = buf[bufIndex + 1];
                unsigned char r = buf[bufIndex + 2];

                unsigned int pixelColor = (0xFF << 24) | (r << 16) | (g << 8) | b;

                store[storeIndex] = pixelColor;
            }
        }

        delete[] buf;
        close(fd);
        // cout << path << "初始化成功 " << width << "x" << height << endl;
    }
    ~Bmp()
    {
        if (store != nullptr)
        {
            delete[] store;
            store = nullptr;
        }
    }
    bool getHyalineStatus() const { return isHyaline; } // 返回是否为透明背景状态
    unsigned int getExcludeColor() const { return Excludecolor; }
};

#endif